// JavaScript Document

var handler = null;
var apiURL = siteUrl+"/article/loadData";
var topHtml = '';
window.category_id = $('#tiles').attr('category-data');
window.page_num    = 1;
window.page_no     = 1;
window.total       = 100;
window.isLoading   = false;

function getArgs() {
  var args = {};
  var query = location.search.substring(1);
  // Get query string
  var pairs = query.split("&");
  // Break at ampersand
  for(var i = 0; i < pairs.length; i++) {
    var pos = pairs[i].indexOf('=');
    // Look for "name=value"
    if (pos == -1) continue;
      // If not found, skip
      var argname = pairs[i].substring(0,pos);// Extract the name
      var value = pairs[i].substring(pos+1);// Extract the value
      value = decodeURIComponent(value);// Decode it, if needed
      args[argname] = value;// Store as a property
    }
    return args;// Return the object
  }

// Prepare layout options.
var options = {
  autoResize: true, // This will auto-update the layout when the browser window is resized.
  container: $('#tiles'), // Optional, used for some extra CSS styling
  offset: 10, // Optional, the distance between grid items
  itemWidth: 250 // Optional, the width of a grid item
};

/**
 * When scrolled all the way to the bottom, add more tiles.
 */
function onScroll(event) {
  if (window.total < 1) {
    return false;
  }
  
  // Only check when we're not still waiting for data.
  if(!window.isLoading) {
    // Check if we're within 100 pixels of the bottom edge of the broser window.
    var closeToBottom = ($(window).scrollTop() + $(window).height() > $(document).height() - 200);
    if(closeToBottom) {
      loadData();
    }
  }
};

/**
 * Refreshes the layout.
 */
function applyLayout() {
  // Clear our previous layout handler.
  if(handler) handler.wookmarkClear();
  
  // Create a new layout handler.
  handler = $('#tiles .box');
  handler.wookmark(options);
  if (typeof doWookFallCallBack == 'function') {
    doWookFallCallBack();
  }
};

/**
 * Loads data from the API.
 */
function loadData() {
  if ($(".box").length >= 60) {
    return false;
  }
  var get = getArgs();
  if (get.ture_nav) {
    window.order = get.ture_nav;
  } else {
    window.order = 'all-true';
  }
  if (get.page_no) {
    window.page_no = get.page_no;
  } else {
    window.page_no = 1;
  }

  window.isLoading = true;
  $('.js_isLoading').show();
  topHtml = '';
  $.ajax({
    url: apiURL,
    type    : 'post',
    dataType: 'json',
    data: { 'page_no': window.page_no, 'page_num':window.page_num, 'category_id':window.category_id }, // Page parameter to make sure we load new data
    success: onLoadData
  });
};

/**
 * Receives data from the API, creates HTML for images and updates the layout
 */
function onLoadData(json) {
  //alert(json.total);
  window.isLoading = false;
  $('.js_isLoading').hide();
  if (json.info != 'ok') {
    // showMsg(json.info);
    $('.js_noMoreThread').css({ display:'block' });
    return false;
  }
  
  if (json.total >= 1) {
    // Create HTML for the images.
    var html = '';
    var i=0, length=json.count, image;
    if (length < 1) {
      $(".js_noMoreThread").show();
    }
    
    for(i; i<length; i++) {
      if (i == 3 && window.page_num == 1) {
        html += topHtml;
      }
      var info = json.data[i];
      var image = new Image();
      image.src = info.small_pic;
      image.onload = function(){
        // Apply layout.
        applyLayout();
      };
      html += '<li class="box">\
          <div class="pic"><a href="'+siteUrl+'/article/'+info.id+'"><img src="'+ info.cover +'" width="250"></a></div>\
          <div class="txt">'+ info.intro +'</div>\
        </li>';
    }
    
    // Add image HTML to the page.
    $item = $(html).hide();
    $('#tiles').append($item);
    $item.fadeIn();
    //  ifrH({ type: "onload" });
    //  ifrH();
    //if(json.page_num >= 6){
      //$('.page').show();
      //window.isLoading = true;
    //} else{
      //$('.page').hide();
      window.isLoading = false;
    //}
    // page ++
    window.page_num++;
    
    // Apply layout.
    applyLayout();
  } else {
    window.total = 0;
    if (window.page_num == 1) {
      $(".js_emptyThread").show();
    }
  }
};

$(function(){
  // Load first data from the API.
  loadData();
  // Capture scroll event.
  $(window).bind('scroll',onScroll);
});